<template>
  <div class="page-container">
    <page-form :model="form" ref="formRef" :rules="rules" layout="vertical">
      <card title="申请信息">
        <page-form-row>
          <page-form-item field="type" label="商户主体类型" :rules="{ required: true, message: '请选择' }" style="width: 400px">
            <a-radio-group v-model="form.type" :options="dict.epType" @change="(value) => changeFn(value)" />
          </page-form-item>
        </page-form-row>
      </card>
      <card title="经营信息">
        <page-form-row>
          <page-form-item
            field="licenseFileId"
            label="营业执照"
            size="1"
            :rules="[{ required: true, message: '请上传照片' }]"
            style="position: relative"
            v-if="form.type === 1 || form.type === 2"
          >
            <span class="common-desc">（仅支持JPG、PNG、BMP格式）</span>
            <upload-ocr v-model="form.licenseFileId" maxMB="5" ocrType="license" @ocrClick="licenseChange" types="JPG、PNG、BMP" />
          </page-form-item>

          <page-form-item
            v-if="form.type === 1 || form.type === 2"
            style="position: relative"
            label="营业执照名称"
            field="licenseName"
            :rules="[{ required: true, message: '请输入' }]"
          >
            <span class="common-desc" style="left: 102px">营业执照上的公司名称</span>
            <i-input v-model="form.licenseName" max-length="50" />
          </page-form-item>
          <page-form-item
            v-if="form.type === 1 || form.type === 2"
            style="position: relative"
            label="注册号"
            field="registerNo"
            :rules="[{ required: true, message: '请输入' }]"
          >
            <span class="common-desc" style="left: 60px">营业执照上的统一社会信用代码</span>
            <i-input v-model="form.registerNo" max-length="18" />
          </page-form-item>

          <page-form-item style="position: relative" field="epName" label="商户名称" :rules="[{ required: true, message: '请输入' }]">
            <span class="common-desc" style="left: 75px; width: 225px">用于在支付完成页和账单中向扫码人展示</span>
            <i-input v-model="form.epName" max-length="50" />
          </page-form-item>
          <page-form-item style="position: relative" label="商户简称" field="epSimple" :rules="[{ required: true, message: '请输入' }]">
            <span class="common-desc" style="left: 75px; width: 225px">用于在支付完成页和账单中向扫码人展示</span>
            <i-input v-model="form.epSimple" max-length="20" />
          </page-form-item>
          <page-form-item
            v-if="form.type === 1 || form.type === 2"
            style="position: relative"
            size="2/3"
            label="注册地址"
            field="registerAddress"
            :rules="[{ required: true, message: '请输入' }]"
          >
            <span class="common-desc" style="left: 75px">营业执照上的注册地址/经营场所</span>
            <i-input v-model="form.registerAddress" max-length="50" />
          </page-form-item>
          <page-form-item
            style="position: relative"
            size="1"
            label="经营范围"
            field="busScope"
            :rules="[{ required: true, message: '请输入' }]"
            v-if="form.type === 1 || form.type === 2"
          >
            <span class="common-desc" style="left: 75px">营业执照上的经营范围</span>
            <i-input v-model="form.busScope" max-length="500" />
          </page-form-item>
          <page-form-item field="areaCode" :rules="{ required: true, message: '请选择' }" label="经营省市区">
            <city-cascader-area v-model="form.areaCode" @change="(value, option) => changeCityFn(item, option)" />
          </page-form-item>
          <page-form-item label="经营详细地址" size="2/3" field="busAddress" :rules="[{ required: true, message: '请输入' }]">
            <i-input v-model="form.busAddress" max-length="50" />
          </page-form-item>

          <page-form-item label="门户照片" size="1" style="position: relative; font-weight: 600; height: 22px; margin-bottom: 10px">
            <span class="common-desc">（仅支持JPG、PNG、BMP格式）</span>
          </page-form-item>

          <page-form-item field="doorFileId" label="门头照片" :rules="[{ required: true, message: '请上传照片' }]">
            <upload-ocr v-model="form.doorFileId" maxMB="5" types="JPG、PNG、BMP" />
          </page-form-item>
          <page-form-item field="storeFileId" label="内部照片" :rules="[{ required: true, message: '请上传照片' }]">
            <upload-ocr v-model="form.storeFileId" maxMB="5" types="JPG、PNG、BMP" />
          </page-form-item>
          <page-form-item field="cashFileId" label="收银台照片" :rules="[{ required: true, message: '请上传照片' }]">
            <upload-ocr v-model="form.cashFileId" maxMB="5" types="JPG、PNG、BMP" />
          </page-form-item>
        </page-form-row>
      </card>
      <card title="法人信息">
        <page-form-row>
          <page-form-item label="证件类型" field="cardType" :rules="[{ required: true, message: '请选择' }]">
            <a-select v-model="form.cardType" placeholder="请选择">
              <a-option v-for="item in cardTypeEnum" :key="item.value" :value="item.value" :label="item.label" />
            </a-select>
          </page-form-item>
          <page-form-item
            field="legalPhone"
            label="法人手机号"
            required
            size="1/3"
            style="position: relative"
            :rules="[{ required: true, validator: validateFn, trigger: 'change' }]"
          >
            <span class="common-desc" style="left: 88px; width: 420px">
              用于接收商户对账后台账号密码、收单电子协议签约链接验证码等相关重要信息</span
            >
            <a-input v-model="form.legalPhone" placeholder="请输入" :max-length="11" allow-clear />
          </page-form-item>
          <page-form-item label="证件照片" size="1" style="position: relative; font-weight: 600; height: 22px; margin-bottom: 10px">
            <span class="common-desc">（仅支持JPG、PNG、BMP格式）</span>
          </page-form-item>

          <page-form-item field="cardFrontFileId" label="正面照（人像）" :rules="[{ required: true, message: '请上传照片' }]">
            <upload-ocr
              v-model="form.cardFrontFileId"
              maxMB="5"
              ocrType="cardFrontFileId"
              @ocrClick="cardFrontFileIdChange"
              types="JPG、PNG、BMP"
            />
          </page-form-item>
          <page-form-item field="cardBackFileId" label="反面照（国徽）" :rules="[{ required: true, message: '请上传照片' }]">
            <upload-ocr
              v-model="form.cardBackFileId"
              maxMB="5"
              ocrType="cardBackFileId"
              @ocrClick="cardBackFileIdChange"
              types="JPG、PNG、BMP"
            />
          </page-form-item>

          <!-- 占位符 -->
          <page-form-item label="" size="1" />

          <page-form-item field="cardNo" label="证件号" :rules="[{ required: true, message: '请输入' }]">
            <i-input v-model="form.cardNo" :max-length="18" placeholder="请输入" />
          </page-form-item>
          <page-form-item field="cardPersonName" label="证件人姓名" :rules="[{ required: true, message: '请输入' }]">
            <i-input v-model="form.cardPersonName" :max-length="20" @change="cardPersonNameChange" />
          </page-form-item>
          <page-form-item field="identityExpireTime" label="证件有效期" :rules="[{ required: true, validator: validateDateFn }]">
            <template #label-extra>
              <a-checkbox @change="identityLongChange" v-model="form.identityLong">长期有效</a-checkbox>
            </template>
            <i-range-picker class="w-full" v-model="form.identityExpireTime" @change="identityExpireTimeChange" value-format="YYYY-MM-DD" />
          </page-form-item>
        </page-form-row>
      </card>
      <card title="结算账户">
        <page-form-row>
          <page-form-item field="accountType" label="账户类型" :rules="{ required: true, message: '请选择' }" size="1">
            <a-radio-group v-model="form.accountType" :options="epTypesEnum" />
          </page-form-item>

          <page-form-item
            v-if="form.accountType == 1 && (form.type === 1 || form.type === 2)"
            style="position: relative"
            label="对公账号"
            field="account"
            :rules="[{ required: true, message: '请输入' }]"
          >
            <span class="common-desc" style="left: 75px">用于收款结算银行账号</span>
            <i-input v-model="form.account" max-length="50" />
          </page-form-item>

          <page-form-item
            v-if="form.accountType == 1 && (form.type === 1 || form.type === 2)"
            style="position: relative"
            label="开户支行"
            field="accountSubBranch"
            :rules="[{ required: true, message: '请输入' }]"
          >
            <span class="common-desc" style="left: 75px">请输入完整的开户支行名称</span>
            <i-input v-model="form.accountSubBranch" max-length="50" />
          </page-form-item>
          <page-form-item
            v-if="form.accountType == 1 && (form.type === 1 || form.type === 2)"
            label="开户名称"
            field="apenAccountName"
            :rules="[{ required: true, message: '请输入' }]"
          >
            <i-input v-model="form.apenAccountName" disabled />
          </page-form-item>

          <page-form-item
            v-if="form.accountType == 2"
            style="position: relative"
            label="银行卡号"
            field="account"
            :rules="[{ required: true, message: '请输入' }]"
          >
            <span class="common-desc" style="left: 75px">用于收款结算银行账号</span>
            <i-input v-model="form.account" max-length="50" />
          </page-form-item>
          <page-form-item
            v-if="form.accountType == 2"
            label="开户姓名"
            field="apenAccountName"
            :rules="[{ required: true, message: '请输入' }]"
          >
            <i-input v-model="form.apenAccountName" disabled />
          </page-form-item>

          <page-form-item
            style="position: relative"
            label="结算主体名称"
            field="settleName"
            :rules="[{ required: true, message: '请输入' }]"
          >
            <span class="common-desc" style="left: 102px; width: 210px">用于在系统中操作结算时选择结算主体</span>
            <i-input v-model="form.settleName" max-length="20" />
          </page-form-item>
          <page-form-item field="settleWay" label="结算方式" :rules="{ required: true, message: '请选择' }">
            <a-radio-group v-model="form.settleWay" :options="dict.settleWay" />
          </page-form-item>
        </page-form-row>
      </card>
    </page-form>
  </div>
  <page-form-footer @ok="submitFn" :ok-loading="okLoading" />
</template>

<script setup name="AggregationApply">
  import { isMobile } from '@/utils/validate.js'
  import { ref, onMounted } from 'vue'
  import { useRouter } from 'vue-router'
  import { thirdServiceApply, thirdServicePolymerInfo } from '@/api/finance/thirdPayment'
  import useNavigate from '@/hooks/useNavigate'
  import { usePageDict } from '@/hooks/useDict'
  import useUserStore from '@/store/modules/user'
  const userStore = useUserStore()
  userStore.setEpDetail()

  const { navigateBack } = useNavigate()
  const dict = usePageDict('polymerDict')

  // 选择省市区回调
  const changeCityFn = (item, option) => {
    console.log(item, option)
    form.value.provinceCode = option.provinceCode
    form.value.cityCode = option.cityCode
    form.value.countyCode = option.areaCode
  }
  const cardTypeEnum = ref([{ label: '身份证', value: 1 }])

  const validateFn = (value, cb) => {
    if (!value || value == '') {
      cb('请输入')
    } else {
      if (!isMobile(value)) {
        cb('手机号格式不正确')
      } else {
        cb()
      }
    }
  }

  const validateDateFn = (value, cb) => {
    console.log(value)
    if (value && value[0] && value[1]) {
      cb()
    } else {
      cb('请选择')
    }
  }

  // 关于选择日期与选择长期
  const identityLongChange = (e) => {
    form.value.identityLong = e
    if (e) {
      form.value.identityExpireTime[1] = '9999-12-31'
      form.value.cardEndTime = '9999-12-31'
    }
  }
  const identityExpireTimeChange = (e) => {
    if (e) {
      form.value.cardStartDate = e[0]
      form.value.cardEndTime = e[1]
      // 判断是否长期
      if (form.value.cardEndTime == '9999-12-31') {
        form.value.identityLong = true
      } else {
        form.value.identityLong = false
      }
    } else {
      form.value.identityExpireTime = []
      form.value.cardStartDate = undefined
      form.value.cardEndTime = undefined
      form.value.identityLong = false
    }
  }

  const epTypesEnum = ref([
    { label: '对公银行账户', value: 1 },
    { label: '法人个人银行卡', value: 2 },
  ])

  const changeFn = (e) => {
    console.log('e', e)
    if (e == 3) {
      epTypesEnum.value = [{ label: '法人个人银行卡', value: 2 }]
      form.value.accountType = 2
    } else {
      epTypesEnum.value = [
        { label: '对公银行账户', value: 1 },
        { label: '法人个人银行卡', value: 2 },
      ]
    }
  }

  const formRef = ref()
  const okLoading = ref(false)
  const form = ref({
    identityLong: false,
    identityExpireTime: [],
  })

  const submitFn = () => {
    console.log('param', form.value)
    formRef.value.validate((error) => {
      if (!error) {
        okLoading.value = true

        const param = {
          ...form.value,
        }
        console.log('param', param)
        let fetch = thirdServiceApply
        fetch(param)
          .then((res) => {
            console.log(res, 'res')
            okLoading.value = false
            navigateBack()
          })
          .finally(() => {
            okLoading.value = false
          })
      }
    })
  }

  const licenseChange = (e) => {
    console.log('licenseChange', e)
    form.value.licenseName = e.companyName
    form.value.registerAddress = e.address
    form.value.busScope = e.business
    form.value.registerNo = e.creditCode
  }

  const cardFrontFileIdChange = (e) => {
    console.log('cardFrontFileIdChange', e)
    form.value.cardPersonName = e.name
    form.value.cardNo = e.number
    cardPersonNameChange()
  }

  const cardBackFileIdChange = (e) => {
    console.log('cardBackFileIdChange', e)
    form.value.cardStartDate = e.startDate
    form.value.cardEndTime = e.endDate == '长期' ? '9999-12-31' : e.endDate
    form.value.identityExpireTime = [e.startDate, form.value.cardEndTime]
    if (e.endDate == '长期') {
      form.value.identityLong = true
    } else {
      form.value.identityLong = false
    }
  }

  const cardPersonNameChange = () => {
    form.value.apenAccountName = form.value.cardPersonName
  }

  const router = useRouter()
  const id = router.currentRoute.value.params.id

  const getDetails = (id) => {
    thirdServicePolymerInfo(id).then((res) => {
      form.value = res.result
      // 证件有效期
      if (res.result.cardEndTime == '9999-12-31') {
        form.value.identityLong = true
      } else {
        form.value.identityLong = false
      }
      form.value.identityExpireTime = [res.result.cardStartDate, res.result.cardEndTime]
      // 经营省市区
      form.value.areaCode = res.result.countyCode
    })
  }

  onMounted(() => {
    console.log('id', id)
    if (id != 0) {
      // 修改
      getDetails({ id: id })
    } else {
      // 默认为D+1
      form.value.settleWay = 1
      // 默认选中“企业”
      form.value.type = 1
      // 默认选中“对公银行账户”
      form.value.accountType = 1
    }
    // 默认选中身份证
    form.value.cardType = 1
  })
</script>

<style lang="less" scoped>
  .common-desc {
    position: absolute;
    top: 0;
    left: 65px;
    font-weight: 400;
    font-size: 12px;
    color: #86909c;
    line-height: 22px;
  }
</style>
